/**
 * This is the project's main class.
 * 
 * ########## Note: This URL is deprecated - see user documentation on etapps.org #########
 * To include this gadget to your google-account use this url:
 * http://vpn.egotec.com:8081/icebeer/modules/sidebar/gadget.xml
 */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import lib.base.*;

public class MainClass extends HttpServlet
{
	/**
	 * recommended by IDE
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The main method.
	 * 
	 * @param args the arguments
	 * 
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws ClassNotFoundException the class not found exception
	 * 
	 * @return
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException
	{
	}
	
	/**
	 * is called when servlet is started first time
	 */
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		try {
			EgoSystem.startup();
		} catch (Exception e)
		{
			throw new ServletException(e);
		}
	}
	
	/**
	 * doGet
	 * 
	 * server-side parse of a get-request
	 * 
	 * @param request
	 * @param response
	 * 
	 * @throws ServletException
	 * @throws IOException 
	 * 
	 * @return
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		EgoSystem system = new EgoSystem(request, response);
		String template = "";
		
		/*
		 * work
		 */
		try {
			/*
			 * load data objects, do auth ...
			 */
			system.prepend();
			
			/*
			 * let the module work
			 */
			system.work();
			
			// show log
			if (EgoSystem.log() != "")
			{
				throw new EgoException(EgoSystem.log());
			}
		} catch (EgoException e)
		{
			if (e.getMessage().equals( EgoException.CUSTOMER_NOT_EXISTS ))
			{
				request.setAttribute(
					"url"
					, EgoSystem.config.get("host").toString()
						+ EgoSystem.config.get("path").toString()
						+ "html?mdl=register"
				);
				template = "new_customer.jsp";
			} else
			{
				request.setAttribute("msg", e.toString());
				template = "error.jsp";
			}
		} catch (Exception e)
		{
			// TODO @deprecated
			String stack="";
			if (!EgoSystem.log().isEmpty())
			{
				stack += "EgoSystem.log:\n"+EgoSystem.log();
			}
			StackTraceElement[] s = e.getStackTrace();
			for (int i=0;i<s.length;i++)
			{
				stack+=s[i].toString()+"\n";
			}
			request.setAttribute("msg", e.toString()+"<hr/>"+e.getMessage()+"<hr/>"+stack);
			template = "error.jsp";
		}
		
		/*
		 * forward to JSP template
		 */
		if (template.isEmpty())
		{
			template = request.getSession().getAttribute("template").toString();
		}
		RequestDispatcher rd = request.getRequestDispatcher(template);
		rd.forward(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request, response);
	}
}
